set -e

MY_DIR=$(basename "$0" | sed 's/\.sh/.d/g')

bin=$(dirname "$0")
bin=$(
  cd "$bin"
  pwd
)

. meta-lib-static/env/.env

MY_IP=127.0.0.1

export MB_JETTY_PORT=${METABASE_SERVER_PORT}
export MB_DB_TYPE=postgres    
export MB_DB_HOST=$(echo $ACCESS_PG_METABASE_NODES | cut -d: -f1)
export MB_DB_PORT=$(echo $ACCESS_PG_METABASE_NODES | cut -d: -f2)
export MB_DB_DBNAME=${METABASE_SERVER_PG_DBNAME}
export MB_DB_USER=${METABASE_SERVER_PG_USERNAME}
export MB_DB_PASS=${METABASE_SERVER_PG_PASSWORD}

export PGPASSWORD=${METABASE_SERVER_PG_PASSWORD}

echo "  [*] start metabase[${MB_JETTY_PORT}] with PG_URL: ${MB_DB_USER}@${MB_DB_HOST}:${MB_DB_PORT}/${MB_DB_DBNAME}"
DB_CMD="${bin}/../data-tool/db-tool.db-setup-rust METABASE_SERVER postgres"
if [ $($DB_CMD -c "SELECT NULL FROM pg_tables WHERE schemaname='public' AND tablename = 'metabase_database'") = "0" ]; then
    echo "DO DB SETUP..."
    $DB_CMD -c "CREATE SCHEMA IF NOT EXISTS public"
    export ACCESS_PG_METABASE_USERNAME
    cat meta-lib-static/sql/setup/metabase_postgres.sql.tpl | envsubst '$ACCESS_PG_METABASE_USERNAME' > meta-lib-static/sql/setup/metabase_postgres.sql
    $DB_CMD -f meta-lib-static/sql/setup/metabase_postgres.sql
    bash ${bin}/${MY_DIR}/setup.sh &
else
    echo "SKIP DB SETUP..."
fi
java -jar ${ACCESS_STATIC_DIR}/metabase-*.jar
